package com.cicoding.forkjoin;

import java.util.concurrent.RecursiveTask;

public class ForkJoinCalculate extends RecursiveTask<Long> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8049081424771805282L;

	private long start;
	private long end;
	
	private static final long THRESHOLD = 10000;
	
	public ForkJoinCalculate(long start,long end){
		this.start = start;
		this.end = end;
	} 
	
	@Override
	protected Long compute() {
		long length = end - start;
		if (length <= THRESHOLD) {
			
			long sum = 0;
			for (long i = start; i <= end; i++) {
				sum += i;
			}
			return sum;
		}else{
			long middle = (start + end) / 2;
			ForkJoinCalculate forkJoinCalculate = new ForkJoinCalculate(start, middle);
			forkJoinCalculate.fork();  //拆分子任务，同时压入线程队列
			
			ForkJoinCalculate calculate = new ForkJoinCalculate(middle + 1, end);
			calculate.fork();
			
			return forkJoinCalculate.join() + calculate.join();
		}
	}

}
